<?php


namespace app\impl;


use app\common\model\BaseModel;
use app\common\model\BindDiseasePath;
use app\common\model\DiseasePatientTask;
use app\common\model\PatientInfo;
use app\interfaces\Task;
use MongoDB\BSON\ObjectId;
use think\facade\Db;

class ChangeDiseasePath implements Task
{

    public function run(array $data, string $taskId): ?bool
    {
        try {

            $type = explode("_", $data['type']);

            //根据data中的患者ID获取患者是否绑定过随访路径
            $patientInfo = (new PatientInfo())->getPatientInfo($data['patientId'], 3);

            if ($patientInfo["liveStatus"] != 1) {
                return true;
            }
            # 判断患者是否绑定随访路径
            $bindDiseaseList = (new BindDiseasePath())->where("patient_id", "=", $data["patientId"])->select();

            if (empty($bindDiseaseList)) {
                echo "患者：" . $data["patientId"] . "没有绑定慢病随访计划";
                return true;
            }
            foreach ($bindDiseaseList as $k => $v) {
                $taskInfo = [];
                # 根据传递过来的类型 获取数据 如果不能存在 直接continue 然后返回true
                $patientTask = (new DiseasePatientTask())->where("bind_id", "=", new ObjectId($v["id"]))->where("step_type.value", "=", $type[0])->order("id", "asc")->select();
                if (!empty($patientTask)) {
                    foreach ($patientTask as $pk => $pv) {
                        # 判断当前步骤号是否大于目前任务序号
                        if ($pv["step_order"] >= $v["step"]) {
                            # 计算延迟时间

                            $calcPushDate = (new \app\common\business\DiseasePath())->calcPath($patientInfo, $pv["id"], null, '', false);
                            $calcPushDate["bind_id"] = $v["id"];
                            if (!empty($calcPushDate)) {
                                $taskInfo[] = $calcPushDate;
                            }
                        }
                    }
                }
                if (!empty($taskInfo)) {
           
                    $result = (new \app\common\business\DiseasePath())->pushTask($taskInfo);
                }
            }
            return true;
        } catch (\Exception $exception) {
            echo $exception->getMessage();
            return false;
        }
    }
}